rm(list=ls())
library(plyr);library(dplyr)
library(tidyr)
library(igraph)
library(stringr)

#setwd('') #set working directory

dat = readRDS('/Users/jeremyspater/Dropbox/duke/wibbels RA/segregation paper/network/3-6-17 jaipat deid.RDS')

#########################################
#Social
GrSoc = function(x){
  el_bor = cbind(x$code3,as.character(x$G.G2.G2B_Code2))
  el_bor2 = cbind(x$code3,as.character(x$G.G3.G3B_Code2))
  el_vis = cbind(x$code3,as.character(x$I.I7.I7B_Code2))
  
  el = rbind(el_bor, el_bor2, el_vis)
  el = el[complete.cases(el),]
  
  gr = graph_from_edgelist(el,directed=TRUE) %>% simplify(remove.multiple=FALSE, remove.loops=TRUE) 
  V(gr)$Religion=as.character(dat$C.C6[match(V(gr)$name,dat$code3)])
  V(gr)$Neighborhood = paste(x$City[1],x$A.A7[1]) 
  return(gr)
}
#Political
GrPol = function(x){
  el_ser = cbind(x$code3,as.character(x$I.I3_Group.I3B_Code2)) #help getting service
  el_meet = cbind(x$code3,as.character(x$I.I16.I16_Lead.meeting)) #
  el_vote = cbind(x$code3,as.character(x$I.I33B_Code2)) #important in how you vote
  el_lea = cbind(x$code3,as.character(x$I.I25B_Code2)) #leader
  
  el = rbind(el_ser, el_vote, el_lea)
  el = el[complete.cases(el),]
  
  gr = graph_from_edgelist(el,directed=TRUE)
  V(gr)$Religion=as.character(dat$C.C6[match(V(gr)$name,dat$code3)])
  V(gr)$Neighborhood = paste(x$City[1],x$A.A7[1]) 
  return(gr)
}
#Economic
GrEcon = function(x){
  el_job = cbind(x$code3,as.character(x$D.D4.D4B_Code2)) #help getting job
  el_work = cbind(x$code3,as.character(x$D.D8.D8B_Code2)) #work with
  el_unemp = cbind(x$code3,as.character(x$E.E3B_Code2)) #unable to find work
  el_house = cbind(x$code3,as.character(x$H.H7.H7B_Code2)) #sell house
  
  el = rbind(el_job, el_work, el_unemp, el_house)
  el = el[complete.cases(el),]
  
  gr = graph_from_edgelist(el,directed=TRUE)
  V(gr)$Religion=as.character(dat$C.C6[match(V(gr)$name,dat$code3)])
  V(gr)$Neighborhood = paste(x$City[1],x$A.A7[1]) 
  return(gr)
}

#create "graphs" for each set of questions
SocList = dlply(dat, 'A.A7', function(x) GrSoc(x))
PolList = dlply(dat, 'A.A7', function(x) GrPol(x))
EconList = dlply(dat, 'A.A7', function(x) GrEcon(x))

#########################################################################################################
#plotting

Pl3 = function(x){
  plot.igraph(x,vertex.size=5,vertex.label = NA,edge.arrow.size=0.1, edge.width=0.3, edge.lty=1,
              margin = 0.0 , edge.color = 'black', vertex.color = 'gray')
}

PlF3 = function(y){#,d){
  layout(matrix(c(1,2,3,4,5,6,7,8,9), nrow = 3, ncol = 3))
  par(mar = c(0.1,0.1,0.1,0.1))
  l_ply(y, Pl3)
}

png(filename=paste0('../results/F1_',(Sys.time() %>% str_replace_all(c(":" = "-", " " = "_"))),'.png'))

PlF3(SocList)
dev.off()
